package monitor.transmission;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import socio.Entity;
import socio.other.SubjectiveInitiative;

import net.sf.json.JSONObject;

import monitor.basic.Activity;

public class Transmitter implements Runnable {
	private BlockingQueue<Activity> activities = new LinkedBlockingQueue<Activity>();
	private DatagramSocket dataSocket;

	public Transmitter() {
		try {
			dataSocket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		if (activities == null)
			return;
		try {
			while (true) {
				Activity activity = this.activities.take();// block if the queue
															// is empty
				send(activity, activity.getWho());
				List<Entity> whos = activity.getWhos();
				if (whos != null) {
					for (int i = 0; i < whos.size(); i++) {
						send(activity, whos.get(i));
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void send(Activity activity, Entity who)
			throws UnknownHostException, IOException {
		if (who == null || !(who instanceof SubjectiveInitiative))
			return;
		byte[] data = this.serialize(activity);
		InetAddress addr = InetAddress.getByName(who.getIp());
		int port = who.getPort();

		DatagramPacket dataPacket = new DatagramPacket(data, data.length, addr,
				port);
		dataSocket.send(dataPacket);
	}

	private byte[] serialize(Activity activity) {
		JSONObject json = JSONObject.fromObject(activity);
		String strJson = json.toString();
		return strJson.getBytes();
	}

	public void send(Activity activity) {
		this.activities.offer(activity);
	}

}
